package com.nuanshui.heatedloan.task.failover;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import com.rabbitmq.client.Channel;
import com.nuanshui.framework.utils.serializer.SerializationUtils;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.annotation.MqMessageHandler;
import com.nuanshui.heatedloan.task.constant.TaskGlobalParams;
import com.nuanshui.heatedloan.task.failover.strategy.TaskFailStrategy;
import com.nuanshui.heatedloan.task.failover.strategy.TaskFailStrategyFactory;

/**
 * 定时任务执行失败的监听器
 * @param 
 * @author guohao
 * @date 2017年1月4日 下午3:25:23
 * @since $
 */
@MqMessageHandler(TaskGlobalParams.TASK_FAIL_MESSAGE_HANDLER)
public class TaskFailoverListener implements RabbitmqMessageHandler  {

	@Autowired
	private TaskFailStrategyFactory taskFailStrategyFactory;
	
	private Logger logger = LoggerFactory.getLogger(TaskFailoverListener.class);
	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
		try {
			TaskFailMessage taskFailMessage =   (TaskFailMessage) SerializationUtils.deserialize(message.getBody());
			MDC.put(TaskGlobalParams.JOB_LOG_CODE_KEY,taskFailMessage.getCode());
			logger.info("------------------------接收到重试消息-------------------------------");
			TaskFailStrategy taskFailStrategy =  taskFailStrategyFactory.createTaskFailStrategy(taskFailMessage);
		    taskFailStrategy.handler(taskFailMessage);
		    logger.info("-------------------------重试策略执行结束--------------------------------");
		} catch (Exception e) {
			e.printStackTrace();
		}	
	    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);		
	}

}
